package top.itaso.lib.widget;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

/**
 * @Description:
 * @Author dengfu.su
 * @Date 2022/10/29
 */
public class CommonDialog {
    private String title = "";
    private String message = "";
    /**
     * 赞成的按钮文案
     */
    private String positive = "";
    /**
     * 否定的按钮文案
     */
    private String negative = "";
    /**
     * 中立性的按钮文案
     */
    private String neutral = "";

    private IPositiveClickListener positiveClickListener;
    private INegativeClickListener negativeClickListener;
    private INeutralClickListener neutralClickListener;

    private View contentView;

    private EDialogDefined dialogDefined = EDialogDefined.original;

    private Context context;

    private AlertDialog dialog;


    /**
     * 确定、赞成的按钮事件监听
     */
    public abstract static class IPositiveClickListener {
        private boolean isDismiss = true;

        /**
         * 用户解决部分业务不能关闭对话框，比如密码校验错误时，对话框是不关闭的
         *
         * @param isDismiss true-关闭对话框，false-不关闭对话框
         */
        public void setDismiss(boolean isDismiss) {
            this.isDismiss = isDismiss;
        }

        public abstract void onClick();
    }

    /**
     * 取消、否定的按钮事件监听
     */
    public interface INegativeClickListener {
        void onClick();
    }

    /**
     * 忽略、中立的按钮事件监听
     */
    public interface INeutralClickListener {
        void onClick();
    }

    public enum EDialogDefined {
        /**
         * 使用原生的 Dialog
         */
        original,
        /**
         * 使用部分自定义 Dialog，自定义部分仅为使用自定义 View 取代原生 Dialog 的 title 和 contentView 部分
         */
        sectional,
        /**
         * 使用完整的自定义部分，即通过自定义 View 实现所有视图和交互
         */
        whole
    }

    private CommonDialog(Builder builder) {
        this.context = builder.context;
        this.dialogDefined = builder.dialogDefined;

        this.title = builder.title;
        this.message = builder.message;

        this.positive = builder.positive;
        this.negative = builder.negative;
        this.neutral = builder.neutral;

        this.positiveClickListener = builder.positiveClickListener;
        this.negativeClickListener = builder.negativeClickListener;
        this.neutralClickListener = builder.neutralClickListener;

        this.contentView = builder.contentView;


    }

    /**
     * Dialog 的整个内容全部重新定义，其中 TitleView 和 FootView 样式已固定
     */
    public void show() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(context, 0);//R.style.Theme_AppCompat
        if (contentView != null) {
            builder.setView(contentView);
        }
        switch (dialogDefined) {
            case original:
                if (!TextUtils.isEmpty(title)) {
                    builder.setTitle(title);
                }
                if (!TextUtils.isEmpty(message)) {
                    builder.setMessage(message);
                }
                //positive、negative、neutral 文案为空时对应原生按钮不显示
                builder
                        .setPositiveButton(positive, new DialogInterface.OnClickListener() {
                            /**
                             * @param dialogInterface
                             * @param which           如 AlertDialog.BUTTON_NEGATIVE
                             */
                            @Override
                            public void onClick(DialogInterface dialogInterface, int which) {
                                if (positiveClickListener != null) {
                                    positiveClickListener.isDismiss = true;
                                    positiveClickListener.onClick();
                                    if (positiveClickListener.isDismiss) {
                                        dialogInterface.dismiss();
                                    }
                                } else {
                                    dialogInterface.dismiss();
                                }

                            }
                        })
                        .setNegativeButton(negative, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int which) {

                                if (negativeClickListener != null) {
                                    negativeClickListener.onClick();
                                }
                                dialogInterface.dismiss();
                            }
                        })
                        .setNeutralButton(neutral, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int which) {
                                if (neutralClickListener != null) {
                                    neutralClickListener.onClick();
                                }
                                dialogInterface.dismiss();
                            }
                        });
                break;
            case sectional:
                break;
            case whole:
                builder.setView(initDialogView(context));
                break;
        }

        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                dialog = null;
            }
        });

        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private View initDialogView(Context context) {
        LinearLayout dialogView = new LinearLayout(context);
        dialogView.setBackgroundColor(context.getResources().getColor(R.color.transparent));
        dialogView.setOrientation(LinearLayout.VERTICAL);
        if (!TextUtils.isEmpty(title)) {
            //添加 TitleView
            dialogView.addView(initTitleView(context));
        }
        //添加 Dialog 内容
        if (contentView != null) {
            dialogView.addView(contentView);
        } else if (!TextUtils.isEmpty(message)) {
            dialogView.addView(createMessageContentTextView(context));
        }
        if (positiveClickListener != null || negativeClickListener != null || neutralClickListener != null) {//事件都没有，说明意图不寻常
            //添加 TitleView
            dialogView.addView(initFootView(context));
        }

        return dialogView;
    }

    /**
     * 创建出对话框的 Title 视图
     *
     * @param context
     * @return
     */
    private View initTitleView(Context context) {
        LinearLayout titleView = new LinearLayout(context);
        titleView.setOrientation(LinearLayout.HORIZONTAL);
        titleView.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp2px(context, 56));
        titleView.setLayoutParams(params);
        titleView.addView(createTitleContentTextView(context));
        return titleView;
    }

    private View initFootView(Context context) {
        LinearLayout footView = new LinearLayout(context);
        footView.setOrientation(LinearLayout.HORIZONTAL);
        footView.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp2px(context, 56));
        footView.setLayoutParams(params);

        if (!TextUtils.isEmpty(neutral)) {
            TextView neutralBtn = createBtnTextView(context);
            neutralBtn.setText(neutral);
            footView.addView(neutralBtn);
            neutralBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    view.requestFocus();
                    if (neutralClickListener != null) {
                        neutralClickListener.onClick();
                    }
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }
            });
        }

        if (!TextUtils.isEmpty(negative)) {
            TextView negativeBtn = createBtnTextView(context);
            negativeBtn.setText(negative);
            footView.addView(negativeBtn);
            negativeBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    view.requestFocus();
                    if (negativeClickListener != null) {
                        negativeClickListener.onClick();
                    }
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }
            });
        }
        if (!TextUtils.isEmpty(positive)) {
            TextView positiveBtn = createBtnTextView(context);
            positiveBtn.setText(positive);
            footView.addView(positiveBtn);
            positiveBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    view.requestFocus();
                    if (positiveClickListener != null) {
                        positiveClickListener.onClick();
                        if (positiveClickListener.isDismiss) {
                            dialog.dismiss();
                        }
                    }

                }
            });
        }

        return footView;
    }


    /**
     * 提供 创建 titlecontent 的视图
     *
     * @return
     */
    private TextView createTitleContentTextView(Context context) {
        TextView textView = new TextView(context);
        textView.setSingleLine();
        textView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        textView.setTextColor(Color.parseColor("#000000"));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        textView.setText(title);
        return textView;
    }


    /**
     * 提供 创建 MessageContent 的视图
     *
     * @return
     */
    private TextView createMessageContentTextView(Context context) {
        TextView textView = new TextView(context);
        textView.setTextColor(Color.parseColor("#000000"));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        textView.setText(message);
//        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimensionPixelSize(R.dimen.));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        int margin = dp2px(context, 20);
        params.setMargins(margin, 0, margin, 0);
        textView.setLayoutParams(params);
        return textView;
    }

    /**
     * 创建 title rightbtn 按钮视图
     *
     * @return
     */
    public TextView createBtnTextView(Context context) {
        TextView textView = new TextView(context);
        textView.setEnabled(true);
        textView.setFocusable(true);
        textView.setSingleLine();
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setBackground(context.getResources().getDrawable(R.drawable.selector_bg_rounded_rectangle_large));
        textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        textView.setGravity(Gravity.CENTER);
        int padding = dp2px(context, 16);
        textView.setPadding(padding, 0, padding, 0);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        textView.setTextColor(context.getResources().getColorStateList(R.color.selector_btn_text_color));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
        params.height = dp2px(context, 30);
        params.width = dp2px(context, 80);
        params.weight = 1;
        int margin = dp2px(context, 30);
        params.setMargins(margin, 0, margin, 0);
        textView.setLayoutParams(params);
        return textView;
    }

    /**
     * 根据分辨率从 dp 的单位 转成为 px(像素)
     */
    private int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static final class Builder {
        private String title = "";//提示
        private String message = "";
        private String positive = "";//确认
        private String negative = "";//取消
        private String neutral = "";//忽略

        private IPositiveClickListener positiveClickListener;
        private INegativeClickListener negativeClickListener;
        private INeutralClickListener neutralClickListener;

        /**
         * 自定义 dialog 内容视图，优先级将高于 content
         */
        private View contentView;

        private Context context;

        private EDialogDefined dialogDefined;

        public Builder(Context context, EDialogDefined dialogDefined) {
            this.context = context;
            this.dialogDefined = dialogDefined;
        }

        public CommonDialog build() {
            return new CommonDialog(this);
        }

        public Builder setTitle(String title) {
            if (!TextUtils.isEmpty(title)) {
                this.title = title;
            }

            return this;
        }

        public Builder setTitle(Context context, int resId) {
            if (resId != 0 && context != null) {
                setTitle(context.getResources().getString(resId));
            }

            return this;
        }

        public Builder setMessage(String message) {
            if (!TextUtils.isEmpty(message)) {
                this.message = message;
            }
            return this;
        }

        public Builder setMessage(Context context, int resId) {
            if (resId != 0 && context != null) {
                setMessage(context.getResources().getString(resId));
            }

            return this;
        }

        public Builder setPositiveClickListener(String positive, IPositiveClickListener listener) {
            if (!TextUtils.isEmpty(positive)) {
                this.positive = positive;
            }
            positiveClickListener = listener;
            return this;
        }

        public Builder setPositiveClickListener(int resId, IPositiveClickListener listener) {
            return setPositiveClickListener(context.getResources().getString(resId), listener);
        }

        public Builder setNegativeClickListener(String negative, INegativeClickListener listener) {
            if (!TextUtils.isEmpty(negative)) {
                this.negative = negative;
            }
            negativeClickListener = listener;
            return this;
        }

        public Builder setNegativeClickListener(int resId, INegativeClickListener listener) {
            return setNegativeClickListener(context.getResources().getString(resId), listener);
        }

        public Builder setNeutralClickListener(String neutral, INeutralClickListener listener) {
            if (!TextUtils.isEmpty(neutral)) {
                this.neutral = neutral;
            }
            neutralClickListener = listener;
            return this;
        }

        public Builder setNeutralClickListener(int resId, INeutralClickListener listener) {
            return setNeutralClickListener(context.getResources().getString(resId), listener);
        }

        /**
         * 自定义 dialog 内容视图，优先级将高于 content
         *
         * @param view
         */
        public Builder setContentView(View view) {
            contentView = view;
            return this;
        }

    }
}
